package com.example.casper.Experiment2024.adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.entity.BookInfo;

import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {

    private List<BookInfo> bookInfoList;
    private OnItemLongClickListener mOnItemLongClickListener;
    private String TAG = "BookAdapter";

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivThumb;
        TextView tvTitle;
        LinearLayout ll;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.ivThumb = (ImageView) itemView.findViewById(R.id.image_view_bool_cover);
            this.tvTitle = (TextView) itemView.findViewById(R.id.text_view_book_name);
            this.ll = (LinearLayout) itemView.findViewById(R.id.ll);
        }
    }

    public BookAdapter(List<BookInfo> bookInfoList) {
        this.bookInfoList = bookInfoList;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BookInfo books = bookInfoList.get(position);
        holder.ivThumb.setImageResource(books.getPhoto());
        holder.tvTitle.setText(books.getTitle());
        holder.ll.setOnLongClickListener(v -> {
            Log.e(TAG, "onItemLongClick:" + position);
            mOnItemLongClickListener.onItemLongClick(v, position);
            return true;
        });
        Log.e(TAG, "onBindViewHolder:" + position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        Log.e(TAG, "onCreateViewHolder");
        return holder;
    }

    @Override
    public int getItemCount() {
        return bookInfoList.size();
    }

    public BookInfo getItem(int position) {
        if (bookInfoList != null && (bookInfoList.size() >= position)) {
            return bookInfoList.get(position);
        }
        return null;
    }

    public interface OnItemLongClickListener {
        void onItemLongClick(View view, int position);
    }

    public void setOnItemLongClickListener(OnItemLongClickListener listener) {
        this.mOnItemLongClickListener = listener;
    }
}